package com.example.oauth2.service;

import com.example.oauth2.entry.Client;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义ClientDetails类
 */
public class CustomClientDetails implements ClientDetails {

    private Client client;

    public CustomClientDetails(Client client) {
        this.client = client;
    }

    @Override
    public String getClientId() {
        return client.getClientId();
    }

    @Override
    public Set<String> getResourceIds() {

        String resourceId[] = client.getResourceId();
        return resourceId == null ? Collections.emptySet() : Arrays.stream(client.getResourceId()).collect(Collectors.toSet());
    }

    @Override
    public boolean isSecretRequired() {
        return true;
    }

    @Override
    public String getClientSecret() {
        return client.getClientSecret();
    }

    @Override
    public boolean isScoped() {
        return client.getScope() != null && !(client.getScope().length > 0);
    }

    @Override
    public Set<String> getScope() {

        String scopes[] = client.getScope();
        return scopes == null ? Collections.emptySet() : Arrays.stream(client.getScope()).collect(Collectors.toSet());
    }

    @Override
    public Set<String> getAuthorizedGrantTypes() {

        String authorizedGrantTypes[] = client.getAuthorizedGrantTypes();
        return authorizedGrantTypes == null ? Collections.emptySet() : Arrays.stream(client.getAuthorizedGrantTypes()).collect(Collectors.toSet());
    }

    @Override
    public Set<String> getRegisteredRedirectUri() {

        String registeredRedirectUri[] = client.getRegisteredRedirectUri();
        return registeredRedirectUri == null ? Collections.emptySet() : Arrays.stream(client.getRegisteredRedirectUri()).collect(Collectors.toSet());
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {

        String authorities[] = client.getAuthorities();

        if (authorities == null) {
            return Collections.emptyList();
        }

        return Arrays.stream(authorities).map(
                a -> (GrantedAuthority) () -> a
        ).collect(Collectors.toList());
    }

    @Override
    public Integer getAccessTokenValiditySeconds() {
        return client.getAccessTokenValiditySeconds();
    }

    @Override
    public Integer getRefreshTokenValiditySeconds() {
        return client.getRefreshTokenValiditySeconds();
    }

    @Override
    public boolean isAutoApprove(String scope) {
        return false;
    }

    @Override
    public Map<String, Object> getAdditionalInformation() {
        return null;
    }
}
